package com.promise.jokerdream.work.signin.newact

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 深渊秘宝工作
class AbyssDrawWork(override val uin: String): BaseWork(uin) {

    override val name: String
        get() = "深渊秘宝"

    override val isActWork: Boolean
        get() = true
    
    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    
    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 先查询深渊秘宝信息
            val queryResult = gameApi.queryAbyssDraw()
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    
                    // 2. 检查三魂抽奖状态
                    if (response.soulFlag == 0) {
                        val soulDrawResult = gameApi.drawAbyss(1) // 1为三魂
                        soulDrawResult.foldWithApiException(
                            onSuccess = { soulResponse ->
                                historyManager.addHistory(name, soulResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                    }
                    
                    // 3. 检查七魄抽奖状态
                    if (response.mortalFlag == 0) {
                        val mortalDrawResult = gameApi.drawAbyss(2) // 2为七魄
                        mortalDrawResult.foldWithApiException(
                            onSuccess = { mortalResponse ->
                                historyManager.addHistory(name, mortalResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                    }
                    
                    WorkResult.Success
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}